<template>
    <div class="location-management-container">
        <pageTitle :title="'工作地點管理'" />

        <!-- 顶部搜索和按钮区域 -->
        <div class="top-action-bar">
            <el-row :gutter="20" align="middle">
                <el-col :span="12">
                    <el-input placeholder="请输入工作地点名称" v-model="searchQuery" class="search-input-with-button" clearable
                        @clear="handleSearch" @keyup.enter="handleSearch">
                        <template #append>
                            <el-button type="primary" @click="handleSearch">
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="12" class="action-buttons">
                    <el-button type="primary" @click="addLocation">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>新增工作地點</span>
                    </el-button>
                    <el-button type="danger" @click="batchDelete" :disabled="selectedLocations.length === 0">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        <span>批量刪除</span>
                    </el-button>
                </el-col>
            </el-row>
        </div>

        <!-- 工作地點表格 -->
        <div class="location-table-card">
            <el-table :data="locationList" style="width: 100%" v-loading="loading" class="no-border-table"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="工作地點名稱" width="180" />
                <el-table-column prop="country" label="國家/地區" width="120" />
                <el-table-column prop="city" label="所在城市" width="150" />
                <el-table-column prop="address" label="詳細地址" />
                <el-table-column prop="postalCode" label="郵政編碼" width="120" />
                <el-table-column prop="type" label="類型" width="120" />
                <el-table-column prop="employeeCount" label="員工數量" width="100" align="center" />
                <el-table-column prop="description" label="描述" show-overflow-tooltip />
                <el-table-column label="操作" width="180" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editLocation(row)">
                            編輯
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteLocation(row)">
                            刪除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-wrapper">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :small="true" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 新增/编辑工作地點对话框 -->
        <el-dialog v-model="locationDialogVisible" :title="isEditMode ? '編輯工作地點' : '新增工作地點'" width="600px">
            <el-form :model="locationForm" :rules="locationRules" ref="locationFormRef" label-width="100px"
                label-position="right">
                <el-form-item label="工作地點" prop="name">
                    <el-input v-model="locationForm.name" placeholder="請輸入工作地點名稱" />
                </el-form-item>

                <el-form-item label="國家/地區" prop="country">
                    <el-select v-model="locationForm.country" placeholder="請選擇國家/地區" @change="handleCountryChange">
                        <el-option v-for="item in countryOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="所在城市" prop="city">
                    <el-cascader v-model="locationForm.city" :options="cityOptions" :props="{ expandTrigger: 'hover' }"
                        placeholder="請選擇省/市/區" style="width: 100%" />
                </el-form-item>

                <el-form-item label="詳細地址">
                    <el-input v-model="locationForm.address" placeholder="請輸入詳細地址" />
                </el-form-item>

                <el-form-item label="郵政編碼">
                    <el-input v-model="locationForm.postalCode" placeholder="請輸入郵政編碼" />
                </el-form-item>

                <el-form-item label="類型">
                    <el-select v-model="locationForm.type" placeholder="請選擇類型">
                        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="描述">
                    <el-input v-model="locationForm.description" type="textarea" :rows="3" placeholder="請輸入描述信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="locationDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitLocationForm">確定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import pageTitle from "@/components/pageTitle/pageTitle.vue"

// 响应式数据
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const selectedLocations = ref([])

// 工作地點列表数据
const locationList = ref([
    {
        id: 1,
        name: '上海總部',
        country: '中國',
        city: ['上海市', '上海市', '浦東新區'],
        address: '張江高科技園區科苑路88號',
        postalCode: '201203',
        type: '總部',
        employeeCount: 350,
        description: '公司主要辦公地點，包含研發中心和行政部門'
    },
    {
        id: 2,
        name: '北京分公司',
        country: '中國',
        city: ['北京市', '北京市', '海淀區'],
        address: '中關村南大街5號',
        postalCode: '100081',
        type: '分公司',
        employeeCount: 120,
        description: '華北地區業務中心'
    },
    {
        id: 3,
        name: '廣州辦事處',
        country: '中國',
        city: ['廣東省', '廣州市', '天河區'],
        address: '珠江新城華夏路10號',
        postalCode: '510623',
        type: '辦事處',
        employeeCount: 45,
        description: '華南地區業務辦事處'
    },
    {
        id: 4,
        name: '香港辦公室',
        country: '中國',
        city: ['香港特別行政區', '香港島', '中西區'],
        address: '中環金融街8號',
        postalCode: '999077',
        type: '國際業務',
        employeeCount: 30,
        description: '國際業務拓展中心'
    },
    {
        id: 5,
        name: '新加坡分部',
        country: '新加坡',
        city: ['新加坡', '中央區', '濱海灣'],
        address: 'Marina Bay Financial Centre',
        postalCode: '018981',
        type: '海外分部',
        employeeCount: 25,
        description: '東南亞業務中心'
    }
])

// 下拉框选项
const countryOptions = ref([
    { value: '中國', label: '中國' },
    { value: '美國', label: '美國' },
    { value: '英國', label: '英國' },
    { value: '日本', label: '日本' },
    { value: '新加坡', label: '新加坡' },
    { value: '澳大利亞', label: '澳大利亞' }
])

const cityOptions = ref([
    {
        value: '北京市',
        label: '北京市',
        children: [
            {
                value: '北京市',
                label: '北京市',
                children: [
                    { value: '東城區', label: '東城區' },
                    { value: '西城區', label: '西城區' },
                    { value: '朝陽區', label: '朝陽區' },
                    { value: '海淀區', label: '海淀區' },
                    { value: '丰台區', label: '丰台區' }
                ]
            }
        ]
    },
    {
        value: '上海市',
        label: '上海市',
        children: [
            {
                value: '上海市',
                label: '上海市',
                children: [
                    { value: '黃浦區', label: '黃浦區' },
                    { value: '徐匯區', label: '徐匯區' },
                    { value: '長寧區', label: '長寧區' },
                    { value: '靜安區', label: '靜安區' },
                    { value: '浦東新區', label: '浦東新區' }
                ]
            }
        ]
    },
    {
        value: '廣東省',
        label: '廣東省',
        children: [
            {
                value: '廣州市',
                label: '廣州市',
                children: [
                    { value: '天河區', label: '天河區' },
                    { value: '越秀區', label: '越秀區' },
                    { value: '海珠區', label: '海珠區' },
                    { value: '荔灣區', label: '荔灣區' }
                ]
            },
            {
                value: '深圳市',
                label: '深圳市',
                children: [
                    { value: '福田區', label: '福田區' },
                    { value: '南山區', label: '南山區' },
                    { value: '羅湖區', label: '羅湖區' }
                ]
            }
        ]
    },
    {
        value: '香港特別行政區',
        label: '香港特別行政區',
        children: [
            {
                value: '香港島',
                label: '香港島',
                children: [
                    { value: '中西區', label: '中西區' },
                    { value: '灣仔區', label: '灣仔區' }
                ]
            },
            {
                value: '九龍',
                label: '九龍',
                children: [
                    { value: '油尖旺區', label: '油尖旺區' },
                    { value: '深水埗區', label: '深水埗區' }
                ]
            }
        ]
    },
    {
        value: '新加坡',
        label: '新加坡',
        children: [
            {
                value: '中央區',
                label: '中央區',
                children: [
                    { value: '濱海灣', label: '濱海灣' },
                    { value: '烏節路', label: '烏節路' }
                ]
            }
        ]
    }
])

const typeOptions = ref([
    { value: '總部', label: '總部' },
    { value: '分公司', label: '分公司' },
    { value: '辦事處', label: '辦事處' },
    { value: '研發中心', label: '研發中心' },
    { value: '海外分部', label: '海外分部' },
    { value: '國際業務', label: '國際業務' }
])

// 表單相關
const locationDialogVisible = ref(false)
const isEditMode = ref(false)
const locationForm = ref({
    id: null,
    name: '',
    country: '',
    city: [],
    address: '',
    postalCode: '',
    type: '',
    description: ''
})
const locationRules = {
    name: [{ required: true, message: '請輸入工作地點名稱', trigger: 'blur' }],
    country: [{ required: true, message: '請選擇國家/地區', trigger: 'change' }],
    city: [{ required: true, message: '請選擇所在城市', trigger: 'change' }]
}
const locationFormRef = ref(null)

// 生命周期钩子
onMounted(() => {
    fetchLocationData()
})

// 方法
const fetchLocationData = () => {
    loading.value = true
    // 模拟API请求
    setTimeout(() => {
        total.value = locationList.value.length
        loading.value = false
    }, 500)
}

const handleSearch = () => {
    currentPage.value = 1
    fetchLocationData()
}

const handleSelectionChange = (selection) => {
    selectedLocations.value = selection
}

const addLocation = () => {
    isEditMode.value = false
    locationForm.value = {
        id: null,
        name: '',
        country: '',
        city: [],
        address: '',
        postalCode: '',
        type: '',
        description: ''
    }
    locationDialogVisible.value = true
}

const editLocation = (row) => {
    isEditMode.value = true
    locationForm.value = { ...row }
    locationDialogVisible.value = true
}

const deleteLocation = (row) => {
    ElMessageBox.confirm(`確定要刪除工作地點「${row.name}」嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        locationList.value = locationList.value.filter(item => item.id !== row.id)
        total.value = locationList.value.length
        ElMessage.success('刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const batchDelete = () => {
    if (selectedLocations.value.length === 0) {
        ElMessage.warning('請至少選擇一個工作地點')
        return
    }

    ElMessageBox.confirm(`確定要刪除選中的 ${selectedLocations.value.length} 個工作地點嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const selectedIds = selectedLocations.value.map(item => item.id)
        locationList.value = locationList.value.filter(item => !selectedIds.includes(item.id))
        selectedLocations.value = []
        total.value = locationList.value.length
        ElMessage.success(`已成功刪除 ${selectedIds.length} 個工作地點`)
    }).catch(() => {
        ElMessage.info('已取消批量刪除')
    })
}

const handleCountryChange = () => {
    // 切換國家時可以重置城市選擇
    locationForm.value.city = []
}

const submitLocationForm = () => {
    locationFormRef.value.validate((valid) => {
        if (valid) {
            if (isEditMode.value) {
                // 更新工作地點
                const index = locationList.value.findIndex(item => item.id === locationForm.value.id)
                if (index !== -1) {
                    locationList.value[index] = { ...locationForm.value }
                }
                ElMessage.success('工作地點更新成功')
            } else {
                // 新增工作地點
                const newId = Math.max(...locationList.value.map(item => item.id), 0) + 1
                locationList.value.push({
                    ...locationForm.value,
                    id: newId,
                    employeeCount: 0
                })
                ElMessage.success('工作地點新增成功')
            }
            locationDialogVisible.value = false
            fetchLocationData()
        }
    })
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchLocationData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchLocationData()
}
</script>

<style scoped lang="less">
.location-management-container {
    padding: 20px;
    background-color: #fff;

    .top-action-bar {
        margin-bottom: 20px;
        padding: 16px 24px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        margin-top: 20px;

        .search-input-with-button {
            max-width: 500px;

            .el-input-group__append {
                background-color: var(--el-color-primary);
                color: white;
                border: none;

                &:hover {
                    opacity: 0.9;
                }
            }
        }

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }
    }

    .location-table-card {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;

        .no-border-table {

            :deep(.el-table__header),
            :deep(.el-table__body),
            :deep(.el-table__row),
            :deep(.el-table__cell) {
                border: none !important;
            }

            :deep(.el-table__header th) {
                background-color: #f4f8ff;
                font-weight: 600;
                padding: 20px;
            }

            :deep(.el-table__row):hover td {
                background-color: #f5f7fa !important;
            }
        }

        .pagination-wrapper {
            margin-top: 24px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>